﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using FBEntities;
using XFControls.Utils;

namespace XDAFacebook
{
    public partial class Authorize : Form
    {
        public string html { get; set; }
        public CookieManager cookieManager { get; set; }
        
        public Authorize()
        {
            InitializeComponent();
            cookieManager = new CookieManager();
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
        }

        private void btAccept_Click(object sender, EventArgs e)
        {

            string loginUrl = "https://www." + Settings.Domain + ".com/connect/uiserver.php";
            string vars = "";

            Regex reg = new Regex(@"<input(?<body>.*?)/>", RegexOptions.Multiline);
            Regex bodyId = new Regex(@"name=""(?<id>.*?)""");
            Regex bodyVal = new Regex(@"value=""(?<value>.*?)"".*?");
            var match = reg.Matches(html);

            foreach (var m in match.Cast<Match>())
            {
                var mbId = bodyId.Match(m.Groups["body"].Value).Groups["id"].Value;
                var mbVal = bodyVal.Match(m.Groups["body"].Value).Groups["value"].Value;

                if (string.IsNullOrEmpty(mbId) || string.IsNullOrEmpty(mbVal) || mbId == "cancel_clicked")
                    continue;

                if (!String.IsNullOrEmpty(vars))
                    vars += "&";
                
                vars += mbId + "=" + Uri.EscapeUriString(mbVal);
            }

            try
            {
                html = WebDownloader.PostData(loginUrl, vars, cookieManager);
            }
            catch(WebException) { }
        }
    }
}